import Vuex from 'vuex'
import { miniLogin, getUserInfo, getDefault } from '@/api/login/index'
import { base_info } from '@/api/moreMessage'

const modulesFiles = import.meta.globEager('./modules/*.ts')
const modules = Object.keys(modulesFiles).reduce((p, n) => {
  const moduleName = n.replace(/^\.\/modules\/(.+)\.ts$/, '$1')
  const value = modulesFiles[n]
  p[moduleName] = value.default
  return p
}, {})

interface state {
  token: string
  platform: string
  userInfo: Object
  safeAreaBottom: number
}

const getters = {}
const state: state = {
  token: '',
  userInfo: {},
  platform: '',
  safeAreaBottom: 0
}
const mutations = {
  setToken(state, payload: string) {
    state.token = payload
  },
  setPlatform(state, payload: string) {
    state.platform = payload
  },
  SET_USERINFO(state, payload: Object) {
    state.userInfo = payload
    if (String(payload) !== '{}') {
      uni.setStorageSync('userInfo', JSON.stringify(payload))
    } else {
      uni.removeStorageSync('userInfo')
    }
  },
  setSafeAreaBottom(state, payload) {
    state.safeAreaBottom = payload
  }
}

const userInfoapi = () => {
  return new Promise((resolve, reject) => {
    if (uni.getStorageSync('token')) {
      getUserInfo()
        .then((res) => {
          if (res) {
            resolve(res.data)
          } else {
            reject()
          }
        })
        .catch((err) => {
          reject()
        })
    } else {
      reject()
    }
  })
}

const actions = {
  async setUserInfo(context) {
    try {
      uni.showLoading({
        title: '登录中...'
      })
      console.log('本地token', uni.getStorageSync('token'))
      let info = await userInfoapi()
      context.commit('SET_USERINFO', info)
      // uni.login({
      //   success: (res) => {
      //     if (res.code) {
      //       miniLogin(res.code).then((res) => {
      //         if (res.code === 0) {
      //           context.commit('SET_USERINFO', res.data)
      //           context.commit('setToken', res.data.token)
      //           info = res.data
      //         }
      //       })
      //     }
      //   }
      // })
      uni.hideLoading()
      let params = {
        userId: info.userId,
        empi: info.empi,
      }
      if (info.phone && info.isVerified && info.isAuthorized) {
        getDefault(params.userId).then((res) => {
          info.patientInfo = Object.assign({}, res.data)
          store.commit('SET_USERINFO', info)
          if (res.data.isFinish || res.data.integrity >= 80) {
            uni.redirectTo({
              url: '/pages/body/index'
            })
          } else {
            uni.redirectTo({
              url: '/pages/dataFix/index'
            })
          }
        })
      } else if (!info.phone) {
        uni.redirectTo({
          url: '/pages/login/login'
        })
      } else if (!info.isVerified) {
        uni.navigateTo({
          url: '/pages/login/realName'
        })
      } else if (!info.isAuthorized) {
        getDefault(params.userId).then((res) => {
          info.patientInfo = Object.assign({}, res.data)
          store.commit('SET_USERINFO', info)
          uni.navigateTo({
            url: '/pages/login/authorization'
          })
        })
      }
    } catch (e) {
      uni.hideLoading()
      uni.login({
        success: (res) => {
          if (res.code) {
            miniLogin(res.code).then((res) => {
              if (res.code === 0) {
                store.commit('SET_USERINFO', res.data)
                store.commit('setToken', res.data.token)
                uni.setStorageSync('token', res.data.token)
                if (getCurrentPages()[0].route == 'pages/login/index') {
                  return
                } else {
                  uni.reLaunch({
                    url: '/pages/login/index'
                  })
                }
              }
            })
          }
        }
      })
    }
  }
}

const store = new Vuex.Store({
  getters,
  state,
  mutations,
  actions,
  modules
})

export default store
